package gui.client;



import system.FieldValidator;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.UIManager;

import java.awt.Color;
import java.awt.SystemColor;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.util.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import javax.swing.border.TitledBorder;
import javax.swing.text.MaskFormatter;

import system.SystemMode;
import system.SystemTypes;
import system.VCP;
import vcpClasses.Client;
import vcpClasses.Order;
import vcpClasses.ParkingLot;
import vcpClasses.Rates;
import vcpClasses.SubscribedClient;

import javax.swing.JFormattedTextField;

import com.toedter.calendar.JDateChooser;
import com.toedter.components.JSpinField;

import control.LoginController;
import control.OrderController;

import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.ImageIcon;

/**
 * this class use to create Advance Order 
 * @author G8
 *
 */
@SuppressWarnings("serial")
public class AdvanceOrderScreen extends JPanel implements ActionListener
{
	public JButton btnLogout;
	public JButton btnBack;
	public JButton btnSave;
	private JTextField IDNumber;
	private JTextField VehiclesNumber;
	private JFormattedTextField Email;
	private JLabel lblIDNumber;
	private JLabel lblVehicleNumber;
	private JLabel lblEMail;
	private JLabel lblCheckOutTime;
	private JLabel lblCheckInTime;
	private JFormattedTextField PaymentAmount;
	private JLabel lblCost;
	private JLabel lblParkingLot;
	private JDateChooser dateOutTime;
	private JSpinField spinField;
	private JDateChooser dateInTime;
	private OrderController orderControl;
	private JComboBox<Integer> cBoxParkingLot;
	private JTextField textCheckOut;
	private JTextField textCheckIn;
	private JButton btnCalculate;
	private SystemTypes ratesResult;
	private String date1;
	private String date2;
	private JButton btnPay;
	/**
	 * Advance Order Screen Constructor 
	 */
	public AdvanceOrderScreen()
	{		
		super();
		initialize();
	}
	/**
	 * This method contains the view of the Panel
	 */
	private void initialize()
	{
		orderControl=new OrderController(null);
		
		setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Order In Advance", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		setBackground(SystemColor.menu);
		setBounds(VCP.guiX,VCP.guiY,500,400);
		setLayout(null);
		VCP.frame.setBounds(this.getBounds());
		
		btnBack = new JButton("Back");
		btnBack.setIcon(new ImageIcon(AdvanceOrderScreen.class.getResource("/img/back.png")));
		btnBack.setSize(150, 30);
		btnBack.setBounds(281, 22, 102, 35);
		btnBack.addActionListener(this);
		add(btnBack);
		
		btnLogout = new JButton("Logout");
		btnLogout.setSize(150, 30);
		btnLogout.setBounds(393, 22, 78, 35);
		btnLogout.addActionListener(this);
		add(btnLogout);
		
		btnSave = new JButton("Create Order");
		btnSave.setEnabled(false);
		btnSave.setBounds(106, 297, 129, 35);
		btnSave.addActionListener(this);
		add(btnSave);
		
		
		IDNumber = new JTextField();
		IDNumber.setBounds(235, 86, 102, 20);
		add(IDNumber);
		
		VehiclesNumber = new JTextField();
		VehiclesNumber.setBounds(235, 116, 102, 20);
		add(VehiclesNumber);
		
		Email = new JFormattedTextField();
		Email.setBounds(235, 235, 178, 20);
		add(Email);
		
		lblIDNumber = new JLabel("ID Number :");
		lblIDNumber.setBounds(75, 86, 160, 14);
		add(lblIDNumber);
		
		lblVehicleNumber = new JLabel("Vehicle Number :");
		lblVehicleNumber.setBounds(75, 116, 160, 14);
		add(lblVehicleNumber);
		
		lblEMail = new JLabel("E-mail :");
		lblEMail.setBounds(75, 235, 160, 14);
		add(lblEMail);
		
		lblCheckOutTime = new JLabel("Check Out Time:");
		lblCheckOutTime.setBounds(75, 206, 160, 14);
		add(lblCheckOutTime);
		
		lblCheckInTime = new JLabel("Check In Time :");
		lblCheckInTime.setBounds(75, 175, 160, 14);
		add(lblCheckInTime);
		
		PaymentAmount = new JFormattedTextField();
		PaymentAmount.setBounds(235, 266, 77, 20);
		PaymentAmount.setEnabled(false);
		add(PaymentAmount);
		
		lblCost = new JLabel("Cost :");
		lblCost.setBounds(75, 266, 160, 14);
		add(lblCost);
		
		lblParkingLot = new JLabel("Parking Lot :");
		lblParkingLot.setBounds(75, 141, 160, 14);
		add(lblParkingLot);
		
		dateOutTime = new JDateChooser();
		dateOutTime.setBounds(336, 205, 77, 20);
		add(dateOutTime);
		
		spinField = new JSpinField();
		spinField.setBounds(336, 339, 23, -6);
		add(spinField);
		
		dateInTime = new JDateChooser();
		dateInTime.setBounds(336, 175, 77, 20);
		add(dateInTime);
		
		cBoxParkingLot = new JComboBox <Integer>();
		cBoxParkingLot.addItem(1);
		cBoxParkingLot.addItem(2);
		cBoxParkingLot.addItem(3);
		cBoxParkingLot.addItem(4);
		cBoxParkingLot.addItem(5);
		cBoxParkingLot.addItem(6);
		cBoxParkingLot.setBounds(235, 141, 84, 20);
		add(cBoxParkingLot);
		
		try 
		{
			MaskFormatter formatCheckInOut = new MaskFormatter("##:##");
			formatCheckInOut.setValidCharacters("0123456789");
			textCheckIn = new JFormattedTextField(formatCheckInOut);
			textCheckOut = new JFormattedTextField(formatCheckInOut);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		textCheckOut.setBounds(235, 203, 77, 20);
		add(textCheckOut);
		textCheckOut.setColumns(10);
		
		textCheckIn.setColumns(10);
		textCheckIn.setBounds(235, 172, 77, 20);
		add(textCheckIn);		
		
		btnCalculate = new JButton("Calculate");
		btnCalculate.setBounds(324, 266, 89, 23);
		btnCalculate.addActionListener(this);
		add(btnCalculate);
		
		btnPay = new JButton("Payment");
		btnPay.setEnabled(false);
		btnPay.setBounds(254, 297, 129, 35);
		btnPay.addActionListener(this);
		add(btnPay);
	}
/**
 * This method listens to the buttons on the panel
 * @param e is the buttons the user Click
 */
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if (e.getSource() == btnCalculate)
		{
			SimpleDateFormat thedate = new SimpleDateFormat("yyyy-MM-dd");
			date1 = thedate.format(dateInTime.getDate());
			date2 = thedate.format(dateOutTime.getDate());
			DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
			DateTime dt1 = formatter.parseDateTime(date1);
			DateTime dt2 = formatter.parseDateTime(date2);
			
			IDNumber.setBackground(Color.WHITE);
			VehiclesNumber.setBackground(Color.WHITE);
			Email.setBackground(Color.WHITE);
			dateInTime.setBackground(Color.WHITE);
			dateOutTime.setBackground(Color.WHITE);
			
			if (FieldValidator.checkNumeric(IDNumber.getText()) && FieldValidator.checkNumeric(VehiclesNumber.getText())
					&& FieldValidator.checkEmail(Email.getText()) && FieldValidator.checkDate(dateInTime.getDate())
					&& FieldValidator.checkDate(dateOutTime.getDate()) && Days.daysBetween(dt1,dt2).getDays()>=0
					&& (Integer.parseInt(IDNumber.getText()) == ((Client)VCP.currentUser).getClientNumber()))
			{				
				ParkingLot lot = new ParkingLot((int)cBoxParkingLot.getSelectedItem());
				SystemTypes lotForRates = new SystemTypes(lot,null);
				ratesResult = orderControl.getRatesForLot(lotForRates);
				PaymentAmount.setText(Float.toString(CalculateCost(((ParkingLot)ratesResult.getObj()).getAdvanceRate())));
				btnPay.setEnabled(true);
			}
			else{
				if (!FieldValidator.checkNumeric(IDNumber.getText())) IDNumber.setBackground(Color.RED);
				if (!FieldValidator.checkNumeric(VehiclesNumber.getText())) VehiclesNumber.setBackground(Color.RED);
				if (!FieldValidator.checkEmail(Email.getText())) Email.setBackground(Color.RED);
				if (!FieldValidator.checkDate(dateInTime.getDate())) dateInTime.setBackground(Color.RED);
				if (!FieldValidator.checkDate(dateOutTime.getDate())) dateOutTime.setBackground(Color.RED);
				JOptionPane.showMessageDialog(null,"Invalid field(s) detected !", "Error",JOptionPane.ERROR_MESSAGE);
			}
				
		}
		if (e.getSource() == btnPay)
		{
			Client client = new Client((Client)VCP.currentUser);
			client.setClientBalance(-1*Float.valueOf(PaymentAmount.getText()));
			SystemTypes clientToPay = new SystemTypes(client,null);
			SystemTypes balanceResult = orderControl.newBalance(clientToPay);
			if (balanceResult.getSysMode().equals(SystemMode.OK)){
				JOptionPane.showMessageDialog(null, balanceResult.getObj().toString(), "Success",JOptionPane.INFORMATION_MESSAGE);
				btnSave.setEnabled(true);
				btnPay.setEnabled(false);
			}
			else
				JOptionPane.showMessageDialog(null,balanceResult.getObj().toString(), "Error",JOptionPane.ERROR_MESSAGE);
		}
		if (e.getSource() == btnSave)
		{			
			Order advanceOrder = new Order(Integer.parseInt(IDNumber.getText()),
					Integer.parseInt(VehiclesNumber.getText()), (int) cBoxParkingLot.getSelectedItem(), 
					textCheckIn.getText(), textCheckOut.getText(), date1,
					date2, Email.getText(),0,"PLANNED","ADVANCE");
			SystemTypes orderToCreate = new SystemTypes(advanceOrder,null);
			SystemTypes setOrderResult = orderControl.createNewOrder(orderToCreate);
			if (setOrderResult.getSysMode().equals(SystemMode.OK))
				{
					JOptionPane.showMessageDialog(null, setOrderResult.getObj().toString(), "Success",JOptionPane.INFORMATION_MESSAGE);
				}
			else
				JOptionPane.showMessageDialog(null,setOrderResult.getObj().toString(), "Error",JOptionPane.ERROR_MESSAGE);

		}
		
		if (e.getSource() == btnBack)
		{
			VCP.setScreen(this, VCP.prevScreen);
			VCP.prevScreen.setBounds(VCP.guiX,VCP.guiY,500,400);
			VCP.prevScreen.setLayout(null);
			VCP.frame.setBounds(VCP.prevScreen.getBounds());
		}
		if (e.getSource() == btnLogout)
		{
			SystemTypes userToLogout = new SystemTypes(VCP.currentUser,null);
			boolean logoutRes = LoginController.LogOut(userToLogout);
			if (logoutRes)
				VCP.setGUI(0, this);
			else
			{
				JOptionPane.showMessageDialog(null, "Failed to logout!", "Error",
	                    JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private float CalculateCost(float rate){
		DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
		DateTime time1 = formatter.parseDateTime(date1 + " " + textCheckIn.getText());
		DateTime time2 = formatter.parseDateTime(date2 + " " + textCheckOut.getText());

		return (((float)Minutes.minutesBetween(time1,time2).getMinutes()/60)*rate);
	}
}
